package org.example.service.imp;

import org.example.dto.UserUsageRecordDTO;
import org.example.dto.ContentRecordDTO;
import org.example.entity.Contents;
import org.example.entity.Users;
import org.example.mapper.ContentsMapper;
import org.example.mapper.UsersMapper;
import org.example.service.UserUsageRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserUsageRecordServiceImpl implements UserUsageRecordService {
    
    @Autowired
    private UsersMapper usersMapper;
    
    @Autowired
    private ContentsMapper contentsMapper;
    
    @Override
    public UserUsageRecordDTO getUserUsageRecordByOpenid(String openid) {
        try {
            // 根据openid查询用户信息
            Users user = usersMapper.getUserByOpenid(openid);
            if (user == null) {
                return null;
            }
            
            return getUserUsageRecordByUserId(user.getId());
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public UserUsageRecordDTO getUserUsageRecordByUserId(Long userId) {
        try {
            // 查询用户信息
            Users user = usersMapper.getUserById(userId);
            if (user == null) {
                return null;
            }
            
            // 查询内容生成记录（用户的所有功能使用记录）
            List<Contents> contents = contentsMapper.getContentsByUserId(userId);
            
            // 统计使用情况
            int totalRecords = contents.size();
            int totalPointsUsed = contentsMapper.getTotalPointsUsedByUserId(userId);
            int successCount = (int) contents.stream().filter(c -> c.getStatus() == 1).count();
            int failedCount = (int) contents.stream().filter(c -> c.getStatus() == 2).count();
            int generatingCount = (int) contents.stream().filter(c -> c.getStatus() == 0).count();
            
            // 构建DTO
            UserUsageRecordDTO dto = new UserUsageRecordDTO();
            dto.setUserId(user.getId());
            dto.setOpenid(user.getOpenid());
            dto.setNickname(user.getNickname());
            dto.setAvatar(user.getAvatar());
            dto.setTotalRecords(totalRecords);
            dto.setTotalPointsUsed(totalPointsUsed);
            dto.setSuccessCount(successCount);
            dto.setFailedCount(failedCount);
            dto.setGeneratingCount(generatingCount);
            
            // 转换记录
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<ContentRecordDTO> recordDTOs = contents.stream()
                    .map(content -> {
                        ContentRecordDTO dto1 = new ContentRecordDTO();
                        dto1.setId(content.getId());
                        dto1.setType(content.getType());
                        dto1.setTitle(content.getTitle());
                        dto1.setPrompt(content.getPrompt());
                        dto1.setResultUrl(content.getResultUrl());
                        dto1.setPointsUsed(content.getPointsUsed());
                        dto1.setStatus(content.getStatus());
                        dto1.setCreatedTime(sdf.format(content.getCreatedTime()));
                        
                        // 设置状态文本
                        switch (content.getStatus()) {
                            case 0:
                                dto1.setStatusText("生成中");
                                break;
                            case 1:
                                dto1.setStatusText("成功");
                                break;
                            case 2:
                                dto1.setStatusText("失败");
                                break;
                            default:
                                dto1.setStatusText("未知");
                        }
                        
                        // 设置类型文本
                        switch (content.getType()) {
                            case 1:
                                dto1.setTypeText("图片");
                                break;
                            case 2:
                                dto1.setTypeText("视频");
                                break;
                            case 3:
                                dto1.setTypeText("对话");
                                break;
                            default:
                                dto1.setTypeText("未知");
                        }
                        
                        return dto1;
                    })
                    .collect(Collectors.toList());
            dto.setRecords(recordDTOs);
            
            return dto;
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public UserUsageRecordDTO getUserUsageRecordByOpenidWithPage(String openid, Integer page, Integer size) {
        try {
            // 根据openid查询用户信息
            Users user = usersMapper.getUserByOpenid(openid);
            if (user == null) {
                return null;
            }
            
            // 计算偏移量
            int offset = (page - 1) * size;
            
            // 查询分页记录
            List<Contents> contents = contentsMapper.getContentsByUserIdWithPage(user.getId(), offset, size);
            
            // 统计总体情况
            List<Contents> allContents = contentsMapper.getContentsByUserId(user.getId());
            int totalRecords = allContents.size();
            int totalPointsUsed = contentsMapper.getTotalPointsUsedByUserId(user.getId());
            int successCount = (int) allContents.stream().filter(c -> c.getStatus() == 1).count();
            int failedCount = (int) allContents.stream().filter(c -> c.getStatus() == 2).count();
            int generatingCount = (int) allContents.stream().filter(c -> c.getStatus() == 0).count();
            
            // 构建DTO
            UserUsageRecordDTO dto = new UserUsageRecordDTO();
            dto.setUserId(user.getId());
            dto.setOpenid(user.getOpenid());
            dto.setNickname(user.getNickname());
            dto.setAvatar(user.getAvatar());
            dto.setTotalRecords(totalRecords);
            dto.setTotalPointsUsed(totalPointsUsed);
            dto.setSuccessCount(successCount);
            dto.setFailedCount(failedCount);
            dto.setGeneratingCount(generatingCount);
            
            // 转换记录
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<ContentRecordDTO> recordDTOs = contents.stream()
                    .map(content -> {
                        ContentRecordDTO dto1 = new ContentRecordDTO();
                        dto1.setId(content.getId());
                        dto1.setType(content.getType());
                        dto1.setTitle(content.getTitle());
                        dto1.setPrompt(content.getPrompt());
                        dto1.setResultUrl(content.getResultUrl());
                        dto1.setPointsUsed(content.getPointsUsed());
                        dto1.setStatus(content.getStatus());
                        dto1.setCreatedTime(sdf.format(content.getCreatedTime()));
                        
                        // 设置状态文本
                        switch (content.getStatus()) {
                            case 0:
                                dto1.setStatusText("生成中");
                                break;
                            case 1:
                                dto1.setStatusText("成功");
                                break;
                            case 2:
                                dto1.setStatusText("失败");
                                break;
                            default:
                                dto1.setStatusText("未知");
                        }
                        
                        // 设置类型文本
                        switch (content.getType()) {
                            case 1:
                                dto1.setTypeText("图片");
                                break;
                            case 2:
                                dto1.setTypeText("视频");
                                break;
                            case 3:
                                dto1.setTypeText("对话");
                                break;
                            default:
                                dto1.setTypeText("未知");
                        }
                        
                        return dto1;
                    })
                    .collect(Collectors.toList());
            dto.setRecords(recordDTOs);
            
            return dto;
        } catch (Exception e) {
            return null;
        }
    }
} 